package com.jinxiangyang.controller;

import cn.hutool.core.io.FileUtil;
import com.jinxiangyang.annotation.OperateLog;
import com.jinxiangyang.utils.MinioUtils;
import com.jinxiangyang.utils.enums.BusinessType;
import com.jinxiangyang.utils.enums.OperatorType;
import com.jinxiangyang.utils.result.AjaxResult;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author jinxiangyang
 * @date 2023/8/21 14:13
 * @description TODO
 **/


@RestController
@RequestMapping("/file")
@Api(tags = "上传文件")
public class UploadFileController {


    @Autowired
    private MinioUtils minioUtils;


    @PostMapping("/upload")
    @OperateLog(title = "上传文件", operatorType = OperatorType.ADMIN, businessType = BusinessType.UPDATE)
    public AjaxResult uploadFile(MultipartFile file)  {
        String uploadFile = null;
        try {
            uploadFile = minioUtils.uploadFile(file);
            return AjaxResult.success(uploadFile);
        } catch (Exception e) {
            return AjaxResult.error("上传失败");
        }
    }



    @GetMapping("/down")
    @OperateLog(title = "上传文件", operatorType = OperatorType.ADMIN, businessType = BusinessType.UPDATE)
    public void delFile(@RequestParam String fileName, HttpServletResponse response){
        InputStream inputStream =null;
        ServletOutputStream outputStream= null;
        try {
            inputStream = minioUtils.downloadFile(fileName);
            outputStream = response.getOutputStream();
            response.setContentType("application/octet-stream;charset=utf-8");
            response.addHeader("Content-Disposition", "attachment; filename=" + fileName+"UTF-8");
            int len=0;
            byte[] buffer = new byte[1024];
            while((len=inputStream.read(buffer))>0) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }



}
